<template>
  <div class="route-generator-container">
    <el-container>
      <el-header class="header">
        <div class="header-content">
          <h1 class="logo">旅游路线规划系统</h1>
          <div class="user-info">
            <el-dropdown @command="handleCommand">
              <span class="user-dropdown">
                <el-icon><User /></el-icon>
                欢迎，{{ username }}
                <el-icon><ArrowDown /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      
      <el-container>
        <el-aside width="200px" class="sidebar">
          <el-menu
            :default-active="activeMenu"
            class="sidebar-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/home">
              <el-icon><House /></el-icon>
              <span>首页</span>
            </el-menu-item>
            <el-menu-item index="/route-generator">
              <el-icon><Location /></el-icon>
              <span>路线生成</span>
            </el-menu-item>
          </el-menu>
        </el-aside>
        
        <el-main class="main-content">
          <div class="generator-section">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-card shadow="hover">
                  <template #header>
                    <div class="card-header">
                      <h3>生成旅游路线</h3>
                    </div>
                  </template>
                  
                  <el-form
                    ref="routeFormRef"
                    :model="routeForm"
                    :rules="routeRules"
                    label-width="100px"
                  >
                    <el-form-item label="目的地" prop="destination">
                      <el-input
                        v-model="routeForm.destination"
                        placeholder="请输入目的地城市，如：西安"
                        clearable
                      />
                    </el-form-item>
                    
                    <el-form-item label="旅行天数" prop="days">
                      <el-input-number
                        v-model="routeForm.days"
                        :min="1"
                        :max="14"
                        placeholder="1-14天"
                        style="width: 100%"
                      />
                    </el-form-item>
                    
                    <el-form-item label="预算等级" prop="budget">
                      <el-select
                        v-model="routeForm.budget"
                        placeholder="请选择预算等级"
                        style="width: 100%"
                      >
                        <el-option label="经济型" value="low" />
                        <el-option label="中等" value="medium" />
                        <el-option label="豪华型" value="high" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="出行人数" prop="people">
                      <el-input-number
                        v-model="routeForm.people"
                        :min="1"
                        :max="10"
                        placeholder="1-10人"
                        style="width: 100%"
                      />
                    </el-form-item>
                    
                    <el-form-item>
                      <el-button
                        type="primary"
                        :loading="generating"
                        @click="generateRoute"
                        style="width: 100%"
                      >
                        生成路线
                      </el-button>
                    </el-form-item>
                  </el-form>
                </el-card>
              </el-col>
              
              <el-col :span="12">
                <el-card shadow="hover" v-if="routeResult">
                  <template #header>
                    <div class="card-header">
                      <h3>生成的路线</h3>
                      <el-button
                        type="success"
                        size="small"
                        @click="validateRoute"
                        :loading="validating"
                      >
                        验证路线
                      </el-button>
                    </div>
                  </template>
                  
                  <div class="route-result">
                    <div class="route-info">
                      <p><strong>目的地：</strong>{{ routeResult.destination }}</p>
                      <p><strong>天数：</strong>{{ routeResult.days }}天</p>
                      <p><strong>预算：</strong>{{ getBudgetText(routeResult.budget) }}</p>
                      <p><strong>人数：</strong>{{ routeResult.people }}人</p>
                    </div>
                    
                    <el-divider />
                    
                    <div class="daily-plans">
                      <h4>每日行程安排</h4>
                      <el-timeline>
                        <el-timeline-item
                          v-for="day in routeResult.data.days"
                          :key="day.day"
                          :timestamp="`第${day.day}天`"
                          placement="top"
                        >
                          <el-card>
                            <h5>景点安排</h5>
                            <ul class="attractions-list">
                              <li v-for="attraction in day.attractions" :key="attraction">
                                {{ attraction }}
                              </li>
                            </ul>
                            <p><strong>住宿：</strong>{{ day.hotel }}</p>
                            <p><strong>预计驾车时间：</strong>{{ day.total_drive_time }}小时</p>
                          </el-card>
                        </el-timeline-item>
                      </el-timeline>
                    </div>
                    
                    <div v-if="validationResult" class="validation-result">
                      <el-divider />
                      <h4>路线验证结果</h4>
                      <el-alert
                        :title="validationResult.is_valid ? '路线合理' : '路线需要调整'"
                        :type="validationResult.is_valid ? 'success' : 'warning'"
                        :description="validationResult.is_valid ? '该路线安排合理，可以执行' : '部分天数安排可能过于紧凑，建议调整'"
                        show-icon
                      />
                    </div>
                  </div>
                </el-card>
                
                <el-card shadow="hover" v-else>
                  <template #header>
                    <div class="card-header">
                      <h3>路线结果</h3>
                    </div>
                  </template>
                  
                  <div class="empty-result">
                    <el-empty description="请填写左侧表单并生成路线" />
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, ArrowDown, House, Location } from '@element-plus/icons-vue'
import { routeAPI } from '../api'

const router = useRouter()
const route = useRoute()

const username = ref('用户')
const generating = ref(false)
const validating = ref(false)
const routeResult = ref(null) as any
const validationResult = ref(null) as any

const routeFormRef = ref()

const routeForm = reactive({
  destination: '',
  days: 3,
  budget: 'medium',
  people: 2
}) as any

const routeRules = {
  destination: [
    { required: true, message: '请输入目的地', trigger: 'blur' }
  ],
  days: [
    { required: true, message: '请选择旅行天数', trigger: 'blur' }
  ],
  budget: [
    { required: true, message: '请选择预算等级', trigger: 'change' }
  ],
  people: [
    { required: true, message: '请选择出行人数', trigger: 'blur' }
  ]
}

const activeMenu = computed(() => route.path)

const getBudgetText = (budget: string) => {
  const budgetMap = {
    low: '经济型',
    medium: '中等',
    high: '豪华型'
  } as any
  return budgetMap[budget] || budget
}

const handleMenuSelect = (index: string) => {
  router.push(index)
}

const handleCommand = async (command: string) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      localStorage.removeItem('token')
      ElMessage.success('已退出登录')
      router.push('/login')
    } catch {
      // 用户取消
    }
  }
}

const generateRoute = async () => {
  if (!routeFormRef.value) return
  
  try {
    await routeFormRef.value.validate()
    generating.value = true
    validationResult.value = null
    
    const response = await routeAPI.generateRoute(routeForm) 
    routeResult.value = {
      ...routeForm,
      ...response.data
    }
    
    ElMessage.success('路线生成成功！')
  } catch (error: any) {
    console.log(error)
    ElMessage.error(error.response?.data?.detail || '路线生成失败，请重试')
  } finally {
    generating.value = false
  }
}

const validateRoute = async () => {
  if (!routeResult.value) return
  
  try {
    validating.value = true
    
    const response = await routeAPI.validateRoute({
      days: routeResult.value.data.days,
      destination: routeResult.value.destination
    })
    
    validationResult.value = response.data
    ElMessage.success('路线验证完成！')
  } catch (error: any) {
    ElMessage.error(error.response?.data?.detail || '路线验证失败，请重试')
  } finally {
    validating.value = false
  }
}
</script>

<style scoped>
.route-generator-container {
  height: 100vh;
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.logo {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: white;
}

.sidebar {
  background-color: #f5f7fa;
  border-right: 1px solid #e4e7ed;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  padding: 20px;
  background-color: #f5f7fa;
}

.generator-section {
  max-width: 1400px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.route-result {
  max-height: 600px;
  overflow-y: auto;
}

.route-info p {
  margin: 8px 0;
  color: #606266;
}

.attractions-list {
  margin: 8px 0;
  padding-left: 20px;
}

.attractions-list li {
  margin: 4px 0;
  color: #606266;
}

.empty-result {
  text-align: center;
  padding: 40px 0;
}

.validation-result {
  margin-top: 20px;
}
</style> 